//精确数字计算
(function () {
    var calc = {
        /**
         *
         四舍六入五考虑，
         五后非零就进一，
         五后皆零看奇偶，
         五前为偶应舍去，
         五前为奇要进一。
         * @param num
         * @param decimalPlaces
         * @returns {number}
         */
        evenRound:function (num, decimalPlaces) {
            var d = decimalPlaces || 0;
            var m = Math.pow(10, d);
            var n = +(d ? num * m : num).toFixed(8); // Avoid rounding errors
            var i = Math.floor(n), f = n - i;
            var e = 1e-8; // Allow for rounding errors in f
            var r = (f > 0.5 - e && f < 0.5 + e) ?
                ((i % 2 == 0) ? i : i + 1) : Math.round(n);
            return d ? r / m : r;
        },

    /*
    函数，加法函数，用来得到精确的加法结果
    说明：javascript的加法结果会有误差，在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。
    参数：arg1：第一个加数；arg2第二个加数；d要保留的小数位数（可以不传此参数，如果不传则不处理小数位数）
    调用：Calc.Add(arg1,arg2,d)
    返回值：两数相加的结果
    */
        Add: function (arg1, arg2) {
            arg1 = arg1.toString(), arg2 = arg2.toString();
            var arg1Arr = arg1.split("."), arg2Arr = arg2.split("."), d1 = arg1Arr.length == 2 ? arg1Arr[1] : "", d2 = arg2Arr.length == 2 ? arg2Arr[1] : "";
            var maxLen = Math.max(d1.length, d2.length);
            var m = Math.pow(10, maxLen);
            var result = Number(((arg1 * m + arg2 * m) / m).toFixed(maxLen));
            var d = arguments[2];
            return typeof d === "number" ? Number((result).toFixed(d)) : result;
        },
        /*
        函数：减法函数，用来得到精确的减法结果
        说明：函数返回较为精确的减法结果。
        参数：arg1：第一个加数；arg2第二个加数；d要保留的小数位数（可以不传此参数，如果不传则不处理小数位数
        调用：Calc.Sub(arg1,arg2)
        返回值：两数相减的结果
        */
        Sub: function (arg1, arg2) {
            return Calc.Add(arg1, -Number(arg2), arguments[2]);
        },
        /*
        函数：乘法函数，用来得到精确的乘法结果
        说明：函数返回较为精确的乘法结果。
        参数：arg1：第一个乘数；arg2第二个乘数；d要保留的小数位数（可以不传此参数，如果不传则不处理小数位数)
        调用：Calc.Mul(arg1,arg2)
        返回值：两数相乘的结果
        */
        Mul: function (arg1, arg2) {
            var r1 = arg1.toString(), r2 = arg2.toString(), m, resultVal, d = arguments[2];
            m = (r1.split(".")[1] ? r1.split(".")[1].length : 0) + (r2.split(".")[1] ? r2.split(".")[1].length : 0);
            resultVal = Number(r1.replace(".", "")) * Number(r2.replace(".", "")) / Math.pow(10, m);
            return typeof d !== "number" ? Number(resultVal) : Number(resultVal.toFixed(parseInt(d)));
        },
        /*
        函数：除法函数，用来得到精确的除法结果
        说明：函数返回较为精确的除法结果。
        参数：arg1：除数；arg2被除数；d要保留的小数位数（可以不传此参数，如果不传则不处理小数位数)
        调用：Calc.Div(arg1,arg2)
        返回值：arg1除于arg2的结果
        */
        Div: function (arg1, arg2) {
            var r1 = arg1.toString(), r2 = arg2.toString(), m, resultVal, d = arguments[2];
            m = (r2.split(".")[1] ? r2.split(".")[1].length : 0) - (r1.split(".")[1] ? r1.split(".")[1].length : 0);
            resultVal = Number(r1.replace(".", "")) / Number(r2.replace(".", "")) * Math.pow(10, m);
            return typeof d !== "number" ? Number(resultVal) : Number(resultVal.toFixed(parseInt(d)));
        }
    };
    window.Calc = calc;
}());
var utils = {
    //刷新页面
    refreshPage: function () {
        window.location.reload();
        return false;
    },
    //返回上一页
    back: function () {
        window.history.back(-1);
    },
    //跳转地址
    urlHref: function (url) {
        window.location.href = url;
    },
    //复选框全选
    checkAll: function (dom) {
        var obj = dom || '#grid';
        $(obj + " :checkbox").prop("checked", true);
    },
    //复选框反选
    checkOther: function (dom) {
        var obj = dom || '#grid';
        $(obj + " :checkbox").each(function () {
            $(this).prop("checked", !$(this).prop("checked"));
        });
    },
    //获取复选框值
    getCheckboxValue: function (dom,type) {
        var obj = dom || '#grid';
        var res = type || 'str';
        var reVal = [];
        $(obj).find("input[type='checkbox']").each(function () {
            if ($(this).prop("checked")) {
                reVal.push($(this).val());
            }
        });
        if(res=='str'){
            return reVal.join(',');
        }else{
            return reVal;
        }
    },
    //检测一条记录
    checkOne: function (reVal) {
        var flag = true;
        if (reVal == undefined || reVal == "") {
            alert('请选择要操作的数据');
            flag = false;
        } else if (reVal.split(",").length > 1) {
            alert('对不起，只能选择一条数据');
            flag = false;
        }
        return flag;
    },
    //检测多条记录
    checkMore: function (reVal) {
        var flag = true;
        if (reVal == undefined || reVal == "") {
            alert('请选择要操作的数据!');
            flag = false;
        }
        return flag;
    },
    //获取json指定列数据
    jsonCol: function (json, col, split) {
        var len = json.length;
        var strsplit = split || ',';
        if (len == 0) {
            return [];
        } else {
            var reval = [];
            for (var i = 0; i < len; i++) {
                reval.push(json[i][col]);
            }
            return reval.join(strsplit);
        }
    },
    //json转字符串
    json2string: function (json) {
        return JSON.stringify(json);
    },
    //时间戳友好显示
    dateDiff: function (timestamp) {
        // 补全为13位
        var arrTimestamp = (timestamp + '').split('');
        for (var start = 0; start < 13; start++) {
            if (!arrTimestamp[start]) {
                arrTimestamp[start] = '0';
            }
        }
        timestamp = arrTimestamp.join('') * 1;
        var minute = 1000 * 60;
        var hour = minute * 60;
        var day = hour * 24;
        var halfamonth = day * 15;
        var month = day * 30;
        var now = new Date().getTime();
        var diffValue = now - timestamp;
        // 如果本地时间反而小于变量时间
        if (diffValue < 0) {
            return '不久前';
        }
        // 计算差异时间的量级
        var monthC = diffValue / month;
        var weekC = diffValue / (7 * day);
        var dayC = diffValue / day;
        var hourC = diffValue / hour;
        var minC = diffValue / minute;

        // 数值补0方法
        var zero = function (value) {
            if (value < 10) {
                return '0' + value;
            }
            return value;
        };
        // 使用
        if (monthC > 12) {
            // 超过1年，直接显示年月日
            return (function () {
                var date = new Date(timestamp);
                return date.getFullYear() + '年' + zero(date.getMonth() + 1) + '月' + zero(date.getDate()) + '日';
            })();
        } else if (monthC >= 1) {
            return parseInt(monthC) + "月前";
        } else if (weekC >= 1) {
            return parseInt(weekC) + "周前";
        } else if (dayC >= 1) {
            return parseInt(dayC) + "天前";
        } else if (hourC >= 1) {
            return parseInt(hourC) + "小时前";
        } else if (minC >= 1) {
            return parseInt(minC) + "分钟前";
        }
        return '刚刚';
    },
    //格式化时间戳
    dateFormat: function (timestamp, formats) {
        // formats格式包括
        // 1. Y-m-d
        // 2. Y-m-d H:i:s
        // 3. Y年m月d日
        // 4. Y年m月d日 H时i分
        formats = formats || 'Y-m-d';

        var zero = function (value) {
            if (value < 10) {
                return '0' + value;
            }
            return value;
        };
        timestamp = timestamp * 1000;
        var myDate = timestamp ? new Date(timestamp) : new Date();

        var year = myDate.getFullYear();
        var month = zero(myDate.getMonth() + 1);
        var day = zero(myDate.getDate());

        var hour = zero(myDate.getHours());
        var minite = zero(myDate.getMinutes());
        var second = zero(myDate.getSeconds());

        return formats.replace(/Y|m|d|H|i|s/ig, function (matches) {
            return ({
                Y: year,
                m: month,
                d: day,
                H: hour,
                i: minite,
                s: second
            })[matches];
        });
    },
    //获取url参数
    getQueryString: function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    },
    //是否手机
    isMobile: function () {
        var ua = navigator.userAgent;
        var ipad = ua.match(/(iPad).*OS\s([\d_]+)/),
            isIphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/),
            isAndroid = ua.match(/(Android)\s+([\d.]+)/),
            isMobile = isIphone || isAndroid;
        if (isMobile) {
            return true;
        } else {
            return false;
        }
    },
    openDialog:function(options){
        var defaultConfig = {
            type:2,
            resize:false,
            offset:'auto'
        };
        var option = $.extend({},defaultConfig,options);
        var index = layer.open(option);
        if(this.isMobile()){
            layer.full(index);
        }
        return index;
    },
    //表单验证
    ajaxSubForm: function (options, dom) {
        var obj = dom || '#form';
        var defaultConfig = {
            btnSubmit: ".btn-sub",
            btnReset: ".btn-reset",
            ajaxPost: true,
            postonce: true,
            tipSweep: false,
            label: '.control-label',
            tiptype: function (msg, o, cssctl) {
                if (o.type == 3) {
                    o.obj.closest('.form-group').addClass('has-error');
                    $(obj).find('.valid-msg').show().html('<i class="fa fa-info-circle"></i> ' + msg);
                } else {
                    o.obj.closest('.form-group').removeClass('has-error');
                    $(obj).find('.valid-msg').html('').hide();
                }
            },
            beforeCheck: function (curform) {
                if (typeof CKEDITOR != 'undefined') { //同步编辑器
                    for (instance in CKEDITOR.instances) {
                        CKEDITOR.instances[instance].updateElement();
                    }
                }
            },
            beforeSubmit: function (curform) {
                $(obj).find('.btn-sub').attr("disabled", "disabled"); //禁用按钮
                $(obj).find('.btn-reset').attr("disabled", "disabled"); //禁用按钮
                $(obj).find("[type='submit']").attr("disabled", "disabled"); //禁用按钮
                $(obj).find("[type='reset']").attr("disabled", "disabled"); //禁用按钮
                layer.load(1);
            },
            callback: function (res) {
                layer.closeAll('loading');
                $(obj).find('.btn-sub').removeAttr("disabled"); //启用按钮
                $(obj).find('.btn-reset').removeAttr("disabled"); //启用按钮
                $(obj).find("[type='submit']").removeAttr("disabled"); //启用按钮
                $(obj).find("[type='reset']").removeAttr("disabled"); //启用按钮
                if (res.code == 1) {
                    if (typeof options == 'function') {
                        options(res);
                    }else{
                        var index = parent.layer.getFrameIndex(window.name);
                        parent.layer.close(index);
                        var callfn = $(obj).data('callfn');
                        if (callfn == "refreshSelfPage") utils.refreshPage();
                        if (callfn == "refreshPage") parent.utils.refreshPage();
                        if (callfn == 'refreshTable') parent.$('#grid').bootstrapTable('refresh');
                        if (callfn == 'url') utils.urlHref(res.url);
                    }
                } else {
                    $(obj).find('.valid-msg').show().html('<i class="fa fa-bell-o"></i> ' + res.msg);
                }
            }
        };
        var config = defaultConfig;
        if (typeof options == 'object') {
            config = $.extend({}, defaultConfig, options);
        }
        In('valid', function () {
            $(obj).Validform(config);
        });
    },
    //ajax封装
    getAjax: function (options) {
        var defaultOptions = {
            type: 'post',
            cache: true,
            async: true,
            dataType: 'json',
            beforeSend: function () {
                layer.load(1);
            },
            error: function () {
                layer.alert('与服务器断开连接！');
                return false;
            },
            complete: function () {
                layer.closeAll('loading');
            }
        };
        var option = $.extend({}, defaultOptions, options);
        $.ajax(option);
    },
    //确认后操作
    doAction: function (obj, callfn) {
        var that = this;
        var msg = $(obj).data('msg') || '确认操作吗？';
        var url = $(obj).data('url');
        var params = $(obj).data('params');
        layer.confirm(msg,{icon:3}, function (index) {
            that.getAjax({
                url: url,
                data: params,
                success: function (res) {
                    layer.close(index);
                    if (res.code == 1) {
                        if (typeof callfn === "function") {
                            callfn(obj, res);
                        } else {
                            if (callfn == "refreshPage") that.refreshPage();
                            if (callfn == 'refreshTable') $('#grid').bootstrapTable('refresh');
                            if (callfn == 'url') that.urlHref(res.url);
                        }
                    } else {
                        layer.msg(res.msg);
                    }
                }
            });
        });
    },
    //表格控件
    btable:function(option,dom){
        var grid=dom || '#grid';
        In.config('serial',true); //串行加载
        In('btable','btable-export','editable','btable-editable',function () {
            var defaultOptions={
                method: 'post', //请求方法
                contentType:'application/x-www-form-urlencoded', //请求方式
                toolbar: ".toolbar", //工具栏
                exportDataType: "all",
                exportTypes: ['json', 'xml', 'csv', 'txt', 'doc', 'excel'],
                sidePagination: 'server',
                queryParamsType:'page',
                pageSize: 15,
                pageList: [10, 25, 50, 'All'],
                showExport: true,
                pagination: true,
                clickToSelect: true, //是否启用点击选中
                singleSelect: true, //是否启用单选
                showRefresh: true,
                showToggle: false,
                showColumns: true,
                pk: 'id',
                mobileResponsive:false,
                queryParams:function (params) {
                    var formData = $('#searchForm').serializeArray();
                    var filter={};
                    var op={};
                    for (var i in formData) {
                        //filter: {"createtime":"2018-10-26 00:00:00 - 2018-10-26 23:59:59","uid":1}
                        //op: {"createtime":"BETWEEN","uid":"="}
                        var opObj = $("[name='"+formData[i].name+"']");
                        var opstr = opObj.data('op');
                        var own = opObj.data('own');
                        var value = formData[i]['value'];
                        if(own=='1') { //单独传输
                            params[formData[i].name] = value;
                        }else{
                            if(!valid.isEmpty(formData[i].name)){
                                op[formData[i].name]=opstr;
                                filter[formData[i].name]=value;
                            }
                        }
                    }
                    params.searchKey=$('#searchKey').val();
                    params.searchValue=$('#searchValue').val();
                    params.filter=filter;
                    params.op=op;
                    return params;
                }
            };
            var options=$.extend({},defaultOptions,option);
            $(grid).bootstrapTable(options);
        });
    },
    //树型表格控件
    bTreeTable:function(option,dom){
        var grid=dom || '#grid';
        In.config('serial',true); //串行加载
        In('btable','treegrid','btable-treegrid','cookie','editable','btable-editable',function () {
            var defaultOptions={
                toolbar: ".toolbar", //工具栏
                clickToSelect: true, //是否启用点击选中
                singleSelect: true, //是否启用单选
                showRefresh: true,
                showToggle: false,
                showColumns: true,
                treeShowField: 'name',
                parentIdField: 'pid',
                onLoadSuccess: function(data) {
                    $(grid).treegrid({
                        treeColumn: 1,
                        saveState:true,
                        initialState:'collapsed',
                        onChange: function() {
                            $('#grid').bootstrapTable('resetWidth');
                        }
                    });
                }
            };
            var options=$.extend({},defaultOptions,option);
            $(grid).bootstrapTable(options);
        });
    },
    initPage:function (options,dom) {
        var obj = dom || '#page';
        var params = options.params || {};
        In('paginationjs',function () {
            var defaultConfig = {
                locator:'rows',
                totalNumberLocator:function (response) {
                    return response.total;
                },
                className:'paginationjs-theme-green',
                pageSize: 12,
                prevText:'上一页',
                nextText:'下一页',
                ajax: {
                    type:'post',
                    data:params,
                    beforeSend: function() {
                        layer.load(2);
                    },
                    complete:function () {
                        layer.closeAll('loading');
                    }
                }
            };
            var config = $.extend({}, defaultConfig, options);
            $(obj).pagination(config);
        });
    },
    /*截取字符串*/
    msubstr:function (str,start,length,suffix) {
        var start = start || 0;
        var length = length || 10;
        var str_length=str.length;/*字符长度*/
        var new_str=str.substring(parseInt(start),parseInt(start)+parseInt(length));
        if(suffix==1 && str_length>length){
            return new_str+'...';
        }else{
            return new_str;
        }
    },
    /**
     * 格式化金额
     * moneyFormat("12345.675910", 3)，返回12,345.676
     * */
    moneyFormat:function (s,n) {
        n = n > 0 && n <= 20 ? n : 2;
        s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
        var l = s.split(".")[0].split("").reverse(), r = s.split(".")[1];
        t = "";
        for (i = 0; i < l.length; i++) {
            t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "" : "");
        }
        return t.split("").reverse().join("") + "." + r;

    },
    //图片预览
    imgPreview: function (url) {
        if (url == '') {
            layer.msg('请先上传图片');
            return false;
        }
        if (utils.isMobile() == 1) {
            area = "80%";
            width = '100%';
        } else {
            area = '400px';
            width = '400px';
        }
        top.layer.open({
            type:1,
            title: false,
            closeBtn: 0,
            offset:'60px',
            area: area,
            shadeClose: true,
            content: '<img src="' + url + '" style="width:' + width + ';" />'
        });
    },
    //附件下载
    filePreview: function (url) {
        if(url==''){
            layer.msg('附件为空！');
            return false;
        }
        var $form = $('<form method="POST" target="_blank"></form>');
        $form.attr('action', url);
        $form.appendTo($('body'));
        $form.submit();
    },
    //删除行 父级元素是 .item-row 时通用
    delRow: function (obj, callFn) {
        $(obj).closest('.item-row').remove();
        if (typeof callFn != 'undefined') {
            callFn(obj);
        }
    },
    //上移 父级元素是 .item-row 时通用
    upMove: function (obj) {
        var leftMove = $(obj).closest('.item-row');   //当前行
        var prevMove = leftMove.prev('.item-row');               //上一个同级元素
        if (prevMove.length > 0) {                        //存在上一个同级元素
            prevMove.insertAfter(leftMove);           //就把它移动到前面
        }
    },
    //下移 父级元素是 .item-row 时通用
    downMove: function (obj) {
        var rightMove = $(obj).closest('.item-row');
        var nextMove = rightMove.next('.item-row');
        if (nextMove.length > 0) {
            nextMove.insertBefore(rightMove);
        }
    },
    /**
     * 格式化金额
     * moneyFormat("12345.675910", 3)，返回12,345.676
     * */
    moneyFormat:function (s,n) {
        n = n > 0 && n <= 20 ? n : 2;
        s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
        var l = s.split(".")[0].split("").reverse(), r = s.split(".")[1];
        t = "";
        for (i = 0; i < l.length; i++) {
            t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "" : "");
        }
        return t.split("").reverse().join("") + "." + r;

    },
    keepDecimal:function (num,fix) {
        var res = parseFloat(num);
        return res.toFixed(fix);
    },
    avgBillPrice:function (arr,avgMoney,type) { //均摊计算单价
        var res=[];
        var calcType = type || 1;
        switch (calcType) {
            case 1: //[pay_money]
                for(var i=0;i<arr.length;i++){
                    if(parseFloat(avgMoney)>parseFloat(arr[i])){
                        res.push(arr[i]);
                        avgMoney=Calc.Sub(avgMoney,arr[i]);
                    }else{
                        res.push(avgMoney);
                        break;
                    }
                }
                break;
            case 2: //[goods_num,goods_price]
                var total=0;
                $.each(arr,function (index,item) {
                    var mul = Calc.Mul(item[0],item[1],4);
                    total+=mul;
                });
                var subtotal=0;
                for(var i=0;i<arr.length-1;i++){
                    var mul = Calc.Mul(arr[i][0],arr[i][1],2);
                    var div = Calc.Div(Calc.Mul(mul,avgMoney),total,2);
                    subtotal+=div;
                    var s = Calc.Div(div,arr[i][0],5);
                    res.push(s);
                }
                var sub = Calc.Div(Calc.Sub(avgMoney,subtotal,2),arr[arr.length-1][0],5);
                res.push(sub);
                break;
            case 3: //[goods_num,goods_price,goods_rate]
                var total=0;
                $.each(arr,function (index,item) {
                    var mul = Calc.Mul(Calc.Mul(item[0],item[1],4),Calc.Add(1,item[2],4)) ;
                    total+=mul;
                });
                var subtotal=0;
                for(var i=0;i<arr.length-1;i++){
                    var mul = Calc.Mul(Calc.Mul(arr[i][0],arr[i][1],2),Calc.Add(1,arr[i][2]),2);
                    var div = Calc.Div(Calc.Mul(mul,avgMoney),total,2);
                    subtotal+=div;
                    var s = Calc.Div(div,arr[i][0],5);
                    res.push(s);
                }
                var sub = Calc.Div(Calc.Sub(avgMoney,subtotal,2),arr[arr.length-1][0],5);
                res.push(sub);
                res = $.map(res,function (item,index) {
                    var result = Calc.Div(item,Calc.Add(1,arr[index][2],4),5);
                    return result;
                });
                break;
        }
        return res;
    }
};
/**
 * 验证
 */
var valid = {
    //是否为空
    isEmpty: function (str) {
        if (str == "" || str == null || str == undefined) { // "",null,undefined
            return true;
        } else {
            return false;
        }
    },
    //是否为邮件
    isEmail: function (str) {
        var reg = /^\w+((-w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
        if (reg.test(str)) return true;
    },
    //是否为手机号
    isPhone: function (str) {
        var a = /^1\d{10}$/, s = $.trim(str);
        if (a.test(s)) return true;
    },
    //是否汉字
    isCN: function (str) {
        var s = $.trim(str), reg = /^[\u4e00-\u9fa5]+$/;
        if (reg.test(s)) return true;
        else return false;
    },
    //是否密码
    isPwd: function (str) {
        var reg = /^[A-Za-z0-9_-]+$/;
        if (reg.test(str)) return true;
    },
    //是否为微信号
    isWx: function (str) {
        var rex = /^[a-zA-Z\d_]{5,}$/;
        if (rex.test($.trim(str))) return true;
        return false;
    },
    //是否全为数字
    isNum: function (num) {
        var rex = /^[0-9]+$/;
        if (rex.test($.trim(num))) return true;
        return false;
    },
    //是否为热线电话
    isPhone: function (num) {
        var rex = /^[0-9]([0-9]|-)*[0-9]$/;
        if (rex.test($.trim(num))) return true;
        return false;
    },
    //是否为钱数
    isFloat: function (n) {
        return !isNaN(n);
    },
    //判断是否为url地址
    isUrl: function (str) {
        var rex = /^(http|https){1}:\/\/[^\s]+$/;
        if (rex.test($.trim(str))) return true;
        else return false;
    }
};
/**
 * 表单辅助
 */
var formHelper = {
    initForm: function () {
        var that = this;
        that.colorpicker();
        that.cxselect();
        that.iCheck();
        that.laydate();
        that.selectpage();
        that.uploadImage();
        that.uploadFile();
        that.uploadMultiImage();
        that.uploadMultiImageDesc();
        that.tags();
        that.inputArray();
        that.uploadMultiFile();
        that.switch();
        that.ckeditor();
    },
    codeEditor:function(id,mode){
        //是否装载静态资源
        if(typeof CodeMirror!='undefined'){
            var codeEditor = CodeMirror.fromTextArea(document.getElementById(id), {
                lineNumbers: true,     // 显示行数
                indentUnit: 4,         // 缩进单位为4
                styleActiveLine: true, // 当前行背景高亮
                matchBrackets: true,   // 括号匹配
                mode: mode, // 代码模式
                lineWrapping: true,    // 自动换行
                theme: 'monokai',      // 使用monokai模版
                smartIndent: true,  // 是否智能缩进
                autoCloseTags:true, //自动闭合标签
                matchTags: {bothTags: true},
                //代码折叠
                foldGutter: true,
                gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter", "CodeMirror-lint-markers"],
                lint: true
            });
            return codeEditor;
        }
    },
    colorpicker:function(){
        if ($('.f-colorpicker').length > 0) {
            In('colorpicker', function () {
                $('.f-colorpicker').colorpicker();
            });
        }
    },
    //icheck
    iCheck: function (skin) {
        if ($('.f-icheck').length > 0) {
            In('iCheck', function () {
                var selectSkin = skin || "square-blue";
                $('.f-icheck').iCheck({
                    checkboxClass: 'icheckbox_' + selectSkin,
                    radioClass: 'iradio_' + selectSkin
                });
            });
        }
    },
    /*cxselect*/
    cxselect:function () {
        if($('.f-cx-select').length >0 ){
            In('cxselect',function () {
                $('.f-cx-select').each(function () {
                    var id=$(this).attr('id');
                    var selects = $(this).data('selects');
                    var url = $(this).data('url');
                    valid.isEmpty(selects)?$(this).data('selects','prov,city,dist'):'';
                    valid.isEmpty(url)?$(this).data('url','/static/plugins/cxselect/js/cityData.min.json'):'';
                    $('#'+id).cxSelect({
                    },function(api) {
                        cxSelectApi=api;
                    });
                });
            })
        }
    },
    /*switch*/
    switch:function () {
        if ($('.f-switch').length > 0) {
            In('switch', function () {
                $('.f-switch').each(function () {
                    var $option = $(this).data('option');
                    var name = $(this).attr('name');
                    var option = $option || {};
                    var defaultOptions = {
                        onText:"启用",
                        offText:"禁用",
                        onColor:'success',
                        offColor:'danger',
                        size:"mini",
                        onSwitchChange:function(event,state){
                            if (typeof option['callfn'] != 'undefined') {
                                eval(option['callfn'] + '(event, state)');
                            }
                        }
                    };
                    var options = $.extend({}, defaultOptions, option);
                    $('input[name="'+name+'"]').bootstrapSwitch(options);
                })
            });
        }
    },
    //富文本编辑器
    ckeditor: function () {
        if ($('.f-ckeditor').length > 0) {
            In('ckeditor', function () {
                $('.f-ckeditor').each(function () {
                    var name = $(this).attr('name');
                    var $option = $(this).data('option');
                    var toolbar = $(this).data('toolbar');
                    if(valid.isEmpty(toolbar)){
                        var bodyWidth = $(document.body).width();
                        toolbar = bodyWidth <= 1024 ? 'Basic' : 'Full';
                    }
                    var option = valid.isEmpty($option) ? {} : $option;
                    var defaultOptions = {
                        toolbar: toolbar
                    };
                    var options = $.extend({}, defaultOptions, option);
                    var editor = CKEDITOR.replace(name, options);
                    //增加视频按钮
                    editor.ui.addButton && editor.ui.addButton( 'html5video', {
                        label   : 'Video',
                        command : 'html5video'
                    });
                });
            });
        }
    },
    /**
     * 多行数据数组。点击增加一行,
     * 思路：将每行数据内的name使用data-name代替，执行新增和删除行时循环更新每行内的name，加上总的字段名和顺序数字
     * */
    inputArray:function () {
        if($('.f-input-array').length >0 ){
            $('.f-input-array').each(function () {
                var name=$(this).data('name');
                $(this).find('.data-row').each(function (index,element) {
                    $(this).attr('data-index',index);
                    var del ='<a href="javascript:;" onclick="formHelper.inputArrayDelrow(this)" class="del">×</a>';
                    if(index>0 && $(this).find('.del').length==0){
                        $(this).append(del);
                    }
                    $(this).children().each(function (i,v) {
                        var children_name = $(this).data('name');
                        $(this).hasClass('del')?'':$(this).attr('name',name+'['+index+']['+children_name+']');
                    })
                })
            })
        }
    },
    inputArrayAddrow:function (obj) {
        var box =$(obj).closest('.f-input-array');
        var html = box.find('.data-row').html();
        html = '<div class="data-row">'+html+'</div>';
        $(obj).before(html);
        formHelper.inputArray();
        /*清空最后一个元素内的值*/
        box.find('.data-row:last').children().each(function () {
            $(this).val('');
        });
    },
    inputArrayDelrow:function (obj) {
        $(obj).closest('.data-row').remove();
        formHelper.inputArray();
    },
    //日期控件
    laydate: function () {
        if ($('.f-laydate').length > 0) {
            In('laydate', function () {
                $('.f-laydate').each(function () {
                    var $option = $(this).data('option');
                    var option = valid.isEmpty($option) ? {} : $option;
                    var defaultOptions = {
                        elem: this
                    };
                    var options = $.extend({}, defaultOptions, option);
                    laydate.render(options);
                });
            })
        }
    },
    //selectpage控件
    selectpage: function () {
        if ($('.f-selectpage').length > 0) {
            In('selectpage', function () {
                $('.f-selectpage').each(function () {
                    var url = $(this).data('url');
                    var showField = $(this).data('show');
                    var keyField = $(this).data('key');
                    var searchField = $(this).data('search');
                    searchField = searchField || showField;
                    var option = $(this).data('option');
                    option = option || {};
                    var query = $(this).data('query');
                    var custom = $(this).data('custom');
                    query = query || '';
                    custom = custom || '';
                    var defaultOptions = {
                        data: url,
                        showField: showField,
                        keyField: keyField,
                        dropButton: true,
                        multiple: false,
                        maxSelectLimit: 0,
                        andOr: 'AND',
                        pageSize: 10,
                        params: function () {
                            return {searchField:searchField,query: query,custom:custom};
                        },
                        eAjaxSuccess: function (d) {
                            return d ? d : undefined;
                        },
                    };
                    if (typeof option['formatItemFun'] != 'undefined') {
                        defaultOptions.formatItem = function (data) {
                            return eval(option['formatItemFun'] + '(data)');
                        }
                    }
                    if (typeof option['selectFun'] != 'undefined') {
                        defaultOptions.eSelect = function (data) {
                            return eval(option['selectFun'] + '(data)');
                        }
                    }
                    var options = $.extend({}, defaultOptions, option);
                    $(this).selectPage(options);
                });
            });
        }
    },
    //上传图片
    uploadImage: function () {
        if ($('.f-uploadimg').length > 0) {
            In('upload', function () {
                $('.f-uploadimg').each(function () {
                    var id = $(this).attr('id');
                    var $option = $(this).data('option'); //maxsize
                    $option = $option || {};
                    var maxsize = $option['maxsize'] || '10mb';
                    var ext = $option['ext'] || 'jpg,gif,png';
                    var options={
                        runtimes: 'html5,flash,html4',
                        multi_selection: false, //不允许多选
                        browse_button: id,
                        url: '/admin/upload/file.html?ext_type=img',
                        flash_swf_url: '/static/plupload/Moxie.swf',
                        multipart_params: {},
                        filters: {
                            max_file_size: maxsize,
                            mime_types: [
                                {title: "请选择图片", extensions: ext}
                            ]
                        },
                        resize: {
                            width: 1000,
                            crop: false,
                            quality : 90,
                            preserve_headers: true
                        },
                        init: {
                            FilesAdded: function (up, files) {
                                layer.load(1);
                                up.start();
                            },
                            FileUploaded: function (up, file, responseObject) {
                                layer.closeAll('loading');
                                if (responseObject.status === 200) {
                                    var res = JSON.parse(responseObject.response);
                                    if (res.uploaded == 1) {
                                        $('#input-' + id).val(res.url);
                                        if (typeof $option['uploaded'] != 'undefined') {
                                            eval($option['uploaded'] + '(id,res)');
                                        }
                                    } else {
                                        layer.msg(res.error.message);
                                    }
                                } else {
                                    layer.msg('上传服务器无响应！');
                                }
                            },
                            Error: function(up, err) {
                                if(err.code==-200){
                                    layer.msg("文件格式错误，请检查后重新上传!");
                                }
                            }
                        }
                    };
                    var uploader = new plupload.Uploader(options);
                    uploader.init();
                });
            });
        }
    },
    //上传附件
    uploadFile: function () {
        if ($('.f-uploadfile').length > 0) {
            In('upload', function () {
                $('.f-uploadfile').each(function () {
                    var id = $(this).attr('id');
                    var $option = $(this).data('option'); //maxsize
                    $option = $option || {};
                    var maxsize = $option['maxsize'] || '50mb';
                    var ext = $option['ext'] || 'rar,zip,tar,gz,7z,bz2,cab,iso,pem,doc,docx,xls,xlsx,ppt,pptx,pdf,txt,md,jpg,jpeg,png,gif';
                    var options={
                        runtimes: 'html5,flash,html4',
                        multi_selection: false, //不允许多选
                        browse_button: id,
                        url: '/admin/upload/file.html?ext_type=file',
                        flash_swf_url: '/static/plupload/Moxie.swf',
                        multipart_params: {},
                        filters: {
                            max_file_size: maxsize,
                            mime_types: [
                                {title: "请选择附件", extensions: ext}
                            ]
                        },
                        init: {
                            FilesAdded: function (up, files) {
                                layer.load(1);
                                up.start();
                            },
                            FileUploaded: function (up, file, responseObject) {
                                layer.closeAll('loading');
                                if (responseObject.status === 200) {
                                    var res = JSON.parse(responseObject.response);
                                    if (res.uploaded == 1) {
                                        $('#input-' + id).val(res.url);
                                        if (typeof $option['uploaded'] != 'undefined') {
                                            eval($option['uploaded'] + '(id,res)');
                                        }
                                    } else {
                                        layer.msg(res.error.message);
                                    }
                                } else {
                                    layer.msg('上传服务器无响应！');
                                }
                            },
                            Error: function(up, err) {
                                if(err.code==-200){
                                    layer.msg("文件格式错误，请检查后重新上传!");
                                }
                            }
                        }
                    };
                    var uploader = new plupload.Uploader(options);
                    uploader.init();
                });
            });
        }
    },
    //多图上传
    uploadMultiImage: function () {
        if ($('.f-upload-images-box').length > 0) {
            In('upload', function () {
                $('.f-upload-images-box').each(function () {
                    var itemDom=$(this).find('.f-upload-images-item');
                    var id = $(this).data('upload');
                    var name = $(this).data('name');
                    var $option = $(this).data('option'); //maxsize
                    var datatype = $(this).attr('datatype');
                    if(typeof datatype=='undefined'){
                        datatype='';
                    }else{
                        datatype='datatype="'+datatype+'"';
                    }
                    $option = $option || {};
                    var maxsize = $option['maxsize'] || '50mb';
                    var ext = $option['ext'] || 'jpg,gif,png';
                    var options={
                        runtimes: 'html5,flash,html4',
                        multi_selection: true, //允许多选
                        browse_button: id,
                        url: '/admin/upload/file.html?ext_type=img',
                        flash_swf_url: '/static/plupload/Moxie.swf',
                        multipart_params: {},
                        filters: {
                            max_file_size: maxsize,
                            mime_types: [
                                {title: "请选择图片", extensions: ext}
                            ]
                        },
                        resize: {
                            width: 1000,
                            crop: false,
                            quality : 90,
                            preserve_headers: true
                        },
                        init: {
                            FilesAdded: function (up, files) {
                                layer.load(1);
                                up.start();
                            },
                            FileUploaded: function (up, file, responseObject) {
                                layer.closeAll('loading');
                                if (responseObject.status === 200) {
                                    $('.moxie-shim-html5').hide();
                                    var res = JSON.parse(responseObject.response);
                                    if (res.uploaded == 1) {
                                        if (typeof $option['uploaded'] != 'undefined') {
                                            eval($option['uploaded'] + '(id,res)');
                                        } else {
                                            var itemrow = '<li class="item-row">\n' +
                                                '               <input type="hidden" name="' + name + '[]" value="' + res.url + '" '+datatype+'/>\n' +
                                                '               <div class="img-box" style="background-image:url(' + res.url + ')">\n' +
                                                '                    <a href="javascript:;" onclick="utils.upMove(this);"><i class="fa fa-arrow-left"></i></a>\n' +
                                                '                    <a href="javascript:;" onclick="utils.downMove(this);"><i class="fa fa-arrow-right"></i></a>\n' +
                                                '                    <a href="javascript:;" onclick="utils.delRow(this);"><i class="fa fa-trash-o"></i></a>\n' +
                                                '               </div>\n' +
                                                '          </li>';
                                            itemDom.append(itemrow);
                                        }
                                    } else {
                                        layer.msg(res.error.message);
                                    }
                                } else {
                                    layer.msg('上传服务器无响应！');
                                }
                            }
                        }
                    };
                    var uploader = new plupload.Uploader(options);
                    uploader.init();
                });
            });
        }
    },
    //多图上传带描述
    uploadMultiImageDesc: function () {
        if ($('.f-upload-images-remark-box').length > 0) {
            In('upload', function () {
                $('.f-upload-images-remark-box').each(function () {
                    var itemDom=$(this).find('.f-upload-images-item');
                    var id = $(this).data('upload');
                    var name = $(this).data('name');
                    var dom = $('#' + id);
                    var datatype = $(this).attr('datatype');
                    if(typeof datatype=='undefined'){
                        datatype='';
                    }else{
                        datatype='datatype="'+datatype+'"';
                    }
                    var $option = $(this).data('option'); //maxsize
                    $option = $option || {};
                    var maxsize = $option['maxsize'] || '50mb';
                    var ext = $option['ext'] || 'jpg,gif,png';
                    var options={
                        runtimes: 'html5,flash,html4',
                        multi_selection: true, //允许多选
                        browse_button: id,
                        url: '/admin/upload/file.html?ext_type=img',
                        flash_swf_url: '/static/plupload/Moxie.swf',
                        multipart_params: {},
                        filters: {
                            max_file_size: maxsize,
                            mime_types: [
                                {title: "请选择图片", extensions: ext}
                            ]
                        },
                        resize: {
                            width: 1000,
                            crop: false,
                            quality : 90,
                            preserve_headers: true
                        },
                        init: {
                            FilesAdded: function (up, files) {
                                layer.load(1);
                                up.start();
                            },
                            FileUploaded: function (up, file, responseObject) {
                                layer.closeAll('loading');
                                if (responseObject.status === 200) {
                                    $('.moxie-shim-html5').hide();
                                    var res = JSON.parse(responseObject.response);
                                    if (res.uploaded == 1) {
                                        if (typeof $option['uploaded'] != 'undefined') {
                                            eval($option['uploaded'] + '(id,res)');
                                        } else {
                                            var itemrow = '<div class="col-lg-6 col-md-12 col-sm-12 item-row">\n' +
                                                '               <div class="img-box"  style="background-image:url(' + res.url + ')">\n' +
                                                '                        <a href="javascript:;" onclick="utils.upMove(this);"><i class="fa fa-arrow-left"></i></a>\n' +
                                                '                        <a href="javascript:;" onclick="utils.downMove(this);"><i class="fa fa-arrow-right"></i></a>\n' +
                                                '                        <a href="javascript:;" onclick="utils.delRow(this);"><i class="fa fa-trash-o"></i></a>\n' +
                                                '               </div>\n' +
                                                '               <div class="form">\n' +
                                                '                   <div class="form-group">\n' +
                                                '                        <input type="hidden" class="form-control" name="'+name+'[url][]" value="'+res.url+'" '+datatype+'>\n' +
                                                '                        <input type="text" class="form-control" name="'+name+'[title][]" placeholder="请输入图片标题">\n' +
                                                '                   </div>\n' +
                                                '                   <div class="form-group">\n' +
                                                '                        <textarea class="form-control" rows="2" name="'+name+'[remark][]" placeholder="请输入图片摘要"></textarea>\n' +
                                                '                   </div>\n' +
                                                '                   <div class="input-group link-input">\n' +
                                                '                        <span class="input-group-addon"><i class="fa fa-link"></i></span>\n' +
                                                '                        <input type="text" class="form-control" name="'+name+'[href][]" placeholder="请输入链接地址">\n' +
                                                '                   </div>\n' +
                                                '                </div>\n' +
                                                '          </div>';
                                            itemDom.append(itemrow);
                                        }
                                    } else {
                                        layer.msg(res.error.message);
                                    }
                                } else {
                                    layer.msg('上传服务器无响应！');
                                }
                            }
                        }
                    };
                    var uploader = new plupload.Uploader(options);
                    uploader.init();
                });
            });
        }
    },
    //多附件上传
    uploadMultiFile: function () {
        if ($('.f-upload-file-box').length > 0) {
            In('upload', function () {
                $('.f-upload-file-box').each(function () {
                    var itemDom=$(this).find('.f-upload-file-item');
                    var id = $(this).data('upload');
                    var $option = $(this).data('option'); //maxsize
                    var name = $(this).data('name');
                    $option = $option || {};
                    var maxsize = $option['maxsize'] || '50mb';
                    var ext = $option['ext'] || 'rar,zip,tar,gz,7z,bz2,cab,iso,pem,doc,docx,xls,xlsx,ppt,pptx,pdf,txt,md,jpg,jpeg,png,gif';
                    var options={
                        runtimes: 'html5,flash,html4',
                        multi_selection: true, //允许多选
                        browse_button: id,
                        url: '/admin/upload/file.html?ext_type=file',
                        flash_swf_url: '/static/plupload/Moxie.swf',
                        multipart_params: {},
                        filters: {
                            max_file_size: maxsize,
                            mime_types: [
                                {title: "请选择附件", extensions: ext}
                            ]
                        },
                        init: {
                            FilesAdded: function (up, files) {
                                layer.load(1);
                                up.start();
                            },
                            FileUploaded: function (up, file, responseObject) {
                                layer.closeAll('loading');
                                if (responseObject.status === 200) {
                                    $('.moxie-shim-html5').hide();
                                    var res = JSON.parse(responseObject.response);
                                    if (res.uploaded == 1) {
                                        if (typeof $option['uploaded'] != 'undefined') {
                                            eval($option['uploaded'] + '(id,res)');
                                        } else {
                                            var itemrow = '<div class="item-row">\n' +
                                                '               <input type="hidden" name="' + name + '[]" value="' + res.url + '" />\n' +
                                                '               <a href="'+res.url+'" target="_blank" class="file-name">'+ res.url +'</a>\n' +
                                                '               <div class="action-box">\n' +
                                                '                    <a href="javascript:;" onclick="utils.upMove(this);"><i class="fa fa-arrow-up"></i></a>\n' +
                                                '                    <a href="javascript:;" onclick="utils.downMove(this);"><i class="fa fa-arrow-down"></i></a>\n' +
                                                '                    <a href="javascript:;" onclick="utils.delRow(this);"><i class="fa fa-trash-o"></i></a>\n' +
                                                '               </div>\n' +
                                                '          </div>';
                                            itemDom.append(itemrow);
                                        }
                                    } else {
                                        layer.msg(res.error.message);
                                    }
                                } else {
                                    layer.msg('上传服务器无响应！');
                                }
                            }
                        }
                    };
                    var uploader = new plupload.Uploader(options);
                    uploader.init();
                });
            });
        }
    },
    /*tags标签*/
    tags: function () {
        if ($('.f-tags').length > 0) {
            In('tags', function () {
                $('.f-tags').each(function () {
                    var id = $(this).attr('id');
                    var disable = $(this).data('disable');
                    var value = $(this).data('value');
                    var tag = new Tag(id);
                    tag.tagValue  = valid.isEmpty(value)?'':value;
                    if(disable){
                        tag.isDisable = true;
                    }
                    tag.initView();
                });
            })
        }
    },
    inputArray:function(){
        if($('.f-input-array').length >0 ){
            $('.f-input-array').on('click','.btn-del',function () {
                $(this).closest('tr').remove();
                //循环data-row tr重新设置index
                var inputName=$(this).closest('table').data('name');
                $(this).closest('table').find('.data-row tr').each(function (index) {
                    var rowObj=this;
                    $(rowObj).find('.item-input').each(function () {
                        var inputObj = this;
                        var name=$(inputObj).data('name');
                        $(inputObj).attr('name',inputName+'['+index+']'+'['+name+']');
                    });
                });
            });
            $('.f-input-array').on('click','.btn-add',function () {
                var _addObj = this;
                var tdTpl = $(_addObj).closest('.data-row-tpl').find('td');
                var tds=[];
                tdTpl.each(function () {
                    var tdObj = this;
                    if($(tdObj).find('.item-input').length>0){
                        var inputCopy = $(tdObj).find('.item-input').clone(); //查找对应控件
                        inputCopy.attr('value',inputCopy.val());
                        tds.push('<td>'+inputCopy[0].outerHTML+'</td>');
                        $(tdObj).find('.item-input').val(''); //清空控件值
                    }
                });
                tds.push('<td><a href="javascript:;" class="btn btn-danger btn-del"><i class="fa fa-times"></i> </a></td>');
                $(_addObj).closest('table').find('.data-row').append('<tr>'+tds.join('')+'</tr>');
                //循环data-row tr重新设置index
                var inputName=$(this).closest('table').data('name');
                $(this).closest('table').find('.data-row tr').each(function (index) {
                    var rowObj=this;
                    $(rowObj).find('.item-input').each(function () {
                        var inputObj = this;
                        var name=$(inputObj).data('name');
                        $(inputObj).attr('name',inputName+'['+index+']'+'['+name+']');
                    });
                });
            });
        }
    },
    /*单图上传后显示缩略图*/
    showThumb:function (id,data) {
        $('#'+id).addClass('img-upload-over');
        $('#'+id).css('backgroundImage','url('+data.file_url+')');
    },
    /*单图上传后删除*/
    delimg:function (id) {
        $('#'+id).removeClass('img-upload-over');
        $('#'+id).css('backgroundImage','');
        $('#input-'+id).val('');
    }
};

//注册模板使用函数
juicer.register('dateDiff', utils.dateDiff);
juicer.register('dateFormat', utils.dateFormat);
juicer.register('json2string', utils.json2string);